package edu.upol.paradise.hypervisor.protocol;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;

import edu.upol.paradise.utils.HypervisorUtils;

public class Packet {
	static final Logger log = Logger.getLogger(Packet.class);
	
	private String header;
	private int packetSize;
	private String packetData;
	
	public Packet(byte[] header, byte[] size, InputStream is) throws Exception {
		this.setHeader(new String(header, "UTF-8").trim());
		this.packetSize = new Integer(new String(size, "UTF-8").trim()).intValue();
		loadPacketContent(is);
	}
	
	public Packet(){
		
	}

	private void loadPacketContent(InputStream is) throws Exception {
		byte[] data = new byte[packetSize];
		HypervisorUtils.readFully(is, data, 0, packetSize);
		setPacketData(new String(data, "UTF-8"));
	}

	public String getHeader() {
		return header;
	}

	public void setHeader(String header) {
		this.header = header;
	}

	public String getPacketData() {
		return packetData;
	}

	public void setPacketData(String packetData) {
		this.packetData = packetData;
	}
	
	public byte[] toBytes() throws UnsupportedEncodingException{
		byte[] data = packetData.getBytes("utf-8");
		byte[] content = new byte[20+data.length];
		
		for (int i=0; i<20; i++)
			content[i] = ' ';
		
		byte[] header = getHeader().getBytes("utf-8");
		for (int i=0; i<header.length; i++)
			content[i] = header[i];
		
		byte[] size = new Integer(data.length).toString().getBytes("utf-8");
		for (int i=0; i<size.length; i++)
			content[i+10] = size[i];
		
		for (int i=0; i<data.length; i++)
			content[i+20] = data[i];
		
		return content;
	}
}
